<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>委托管理</span>
      </div>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" style="margin-top: 20px;">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="委托日期">
              <el-date-picker
                  v-model="searchForm.appointmentTime"
                  type="date"
                  placeholder="选择预约日期"
                  :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="房屋类型" prop="description">
              <el-select v-model="searchForm.type" placeholder="请选择房源类型">
                <el-option label="卖房" value="0" />
                <el-option label="租房" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预约状态" prop="description">
              <el-select v-model="searchForm.status" placeholder="请选择房源类型">
                <el-option label="待确认" value="0" />
                <el-option label="已确认" value="1" />
                <el-option label="已取消" value="2" />
                <el-option label="已完成" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="ListArray">搜索</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="clearsearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 表格内容 -->
    <el-table :data="ListData" style="width: 100%" v-loading="loading">
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column label="头像" prop="userCusPic" width="100px">
        <template #default="{ row }">
          <el-image
              style="width: 60px; height: 60px; border-radius: 50%;"
              :src="row.userCusPic"
              v-if="row.userCusPic"
              fit="cover"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无头像</span>
        </template>
      </el-table-column>

      <el-table-column label="昵称" prop="customerName" />
      <el-table-column label="客户电话" prop="cusTel" />
      <el-table-column label="预约时间" prop="appointmentTime" />
      <el-table-column label="房源地址" prop="address" />
      <el-table-column label="小区名称" prop="communityName" />
      <el-table-column label="房源类型">
        <template #default="{ row }">
          <el-tag
              :type="{
              0: 'info',
              1:'success'
            }[row.type]"
          >
            {{
              {
                "0": '卖房',
                "1": '租房',
              }[row.type]
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约状态">
        <template #default="{ row }">
          <el-tag
              :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
          >
            {{
              {
                0: '待确认',
                1: '已确认',
                2: '已取消',
                3: '已完成'
              }[row.status]
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button
              type="success"
              :icon="Check"
              circle
              plain
              @click="handleConfirm(row)"
          ></el-button>
          <el-button
              type="danger"
              :icon="Close"
              circle
              plain
              @click="handleCancel(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无用户数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />

    <router-view></router-view>
  </el-card>
</template>

<script setup>
import {Check, Close} from '@element-plus/icons-vue'
import { ref } from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteAppointmentsService, getAppointmentsPageList, updateAppointmentStatus} from "@/api/appointments.js";
import {deleteHouseService} from "@/api/housesList.js";
import { useUserInfoStore } from "@/stores/userinfo.js";
const userInfoStore = useUserInfoStore()
const userinfoId = userInfoStore.info.id;

const ListData = ref([])
const pageNum = ref(1)
const total = ref(0)
const pageSize = ref(15)
const searchForm = ref({
  intermediaryId:userinfoId,
  appointmentTime: '',
  type:'',
  status:''
})
const loading = ref(false)

// 状态操作处理
const handleConfirm = async (row) => {
  try {
    await updateAppointmentStatus({id:row.id})
    ElMessage.success('预约已确认')
    ListArray()
  } catch (error) {
    // ElMessage.error('操作失败')
  }
}
// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// const handleCancel = async (row) => {
//   try {
//     await deleteAppointmentsService(row.id)
//     ElMessage.success('预约已取消')
//     ListArray()
//   } catch (error) {
//     ElMessage.error('操作失败')
//   }
// }
const handleCancel = (row) => {
  ElMessageBox.confirm('此操作将取消预约申请, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAppointmentsService(row.id)
    ElMessage.success('预约已取消')
    ListArray()
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
// 获取列表数据
const ListArray = async () => {
  loading.value = true
  const params = {
    ...searchForm.value,
    appointmentTime: formatDate(searchForm.value.appointmentTime)
  };
  try {
    const result = await getAppointmentsPageList(
        pageNum.value,
        pageSize.value,
        params
    )
    ListData.value = result.res.items
    total.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}

const clearsearch = () => {
  searchForm.value = {
    appointmentTime: null, // 设为 null 以清空日期选择器
    type: '',
    status: ''
  };
  ListArray();
}

// 初始加载
ListArray()

// 分页处理
const onSizeChange = (size) => {
  pageSize.value = size
  ListArray()
}

const onCurrentChange = (num) => {
  pageNum.value = num
  ListArray()
}
</script>

<!-- 样式部分保持不变 -->

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-tag {
    margin: 2px;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
